library main;

import 'dart:convert';
import 'dart:async';
import 'dart:html';

part 'types.dart';

String base = 'http://www.espncricinfo.com/ci/engine/match/';

List<String> getImpMatches(String allMatches){
  var ret = [];
  Map data = JSON.decode(allMatches);
  List<Map> intl = data['int'];
  for (var each in intl){
    var teams = each['f'].split(' v ');
    if (countries.contains(teams[0]) && 
        countries.contains(teams[1])) ret.add(each['id']);
  }
  return ret;
}

Future<List<Delivery>> getLastDelivs(List<String> impMatches){
  if (impMatches.length == 0) return new Future.error(const FormatException('no live matches'));
  List<Future> futures = new List<Future>();
  for (var each in impMatches) futures.add(client.read('$base$each.json'));
  return Future.wait(futures)
    .then(extractLastDelivs);
}

List<Delivery> extractLastDelivs(List<String> impMatchesData){
  List<Delivery> ret = new List<Delivery>();
  for (var each in impMatchesData){
    Map everything = JSON.decode(each);
    Map lastDelivData = everything['comms'][0]['ball'][0];
    Delivery lastDeliv = new Delivery(lastDelivData);
    ret.add(lastDeliv);
  }
  return ret;
}

void handleLastDelivs(List<Delivery> lastDelivs){
  for (var each in lastDelivs) if (each.isSpecial) print(each);
//    chrome.notifications.create('', new chrome.NotificationOptions(message: each.toString()));
}

void pseudoMain(){
  client.read('${base}matchList.json')
    .then(getImpMatches)
    .then(getLastDelivs)
    .then(handleLastDelivs)
    .catchError((excp){})
    .whenComplete(() {
//      print('cool');
      new Future.delayed(const Duration(seconds: 30), pseudoMain);
    });
}

void main() {
  client = new http.Client();
  pseudoMain();
}
